package com.shxc.smarttrade.old.activity;

import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.HomePagerDatas;
import com.shxc.smarttrade.old.bean.Master;
import com.shxc.smarttrade.old.bean.MasterCopyInfo;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.fragment.SuperDataStatisticsFragment;
import com.shxc.smarttrade.old.fragment.SuperTradeFragment;
import com.shxc.smarttrade.old.fragment.SuperTradeHistoryFragment;
import com.shxc.smarttrade.old.iview.SupermandetailIView;
import com.shxc.smarttrade.old.myview.CustomDialog;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.presenter.MasterDetailPresenter;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.BaseView;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by jcdev1 on 2017/5/16.
 */

public class SupermanDetailActivity extends FragmentActivity implements View.OnClickListener, SupermandetailIView {
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rl_left)
    RelativeLayout rlLeft;
    @BindView(R.id.btn_follow)
    Button btnFollow;
    @BindView(R.id.circle_image)
    CircleImageView circleImage;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_all_yield)
    TextView tvAllYield;
    @BindView(R.id.ll_one)
    LinearLayout llOne;
    @BindView(R.id.ll_two)
    LinearLayout llTwo;
    @BindView(R.id.ll_three)
    LinearLayout llThree;
    @BindView(R.id.iv_tag)
    ImageView ivTag;
    int vari = 0;
    Animation animation = null;
    int offset = 0;
    @BindView(R.id.iv_one)
    ImageView ivOne;
    @BindView(R.id.tv_one)
    TextView tvOne;
    @BindView(R.id.iv_two)
    ImageView ivTwo;
    @BindView(R.id.tv_two)
    TextView tvTwo;
    @BindView(R.id.iv_three)
    ImageView ivThree;
    @BindView(R.id.tv_three)
    TextView tvThree;
    @BindView(R.id.tv_max_retract)
    TextView tvMaxRetract;
    @BindView(R.id.tv_total_close)
    TextView tvTotalClose;
    @BindView(R.id.tv_profit_close_rate)
    TextView tvProfitCloseRate;
    @BindView(R.id.ll_followed)
    LinearLayout llFollowed;
    @BindView(R.id.btn_change_money)
    Button btnChangeMoney;
    @BindView(R.id.btn_remove)
    Button btnRemove;

    private Fragment[] mFragment;
    private SuperDataStatisticsFragment dataStatisticsFragment;
    private SuperTradeFragment tradeFragment;
    private SuperTradeHistoryFragment tradeHistoryFragment;
    private int mIndex;
    public String userCode = "";
    private String userName = "";
    private MyProgressDialog shortDialog;
    private int tag = -1;//区别是跟单还是修改
    private PopupWindow popupWindow = null;
    private MasterDetailPresenter masterDetailPresenter = new MasterDetailPresenter(this);
    private MasterCopyInfo.DataBean.CopyInfoBean masterCopyInfo = null;
    private int userId = -1;
    private String accessToken = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_superman_detail);
        ButterKnife.bind(this);
        CloseAllActivity.getScreenManager().pushActivity(this);
        initView();
        initData();
        initFragment();
        initListener();
    }


    /**
     * 初始化View
     */
    private void initView() {
        tvCenter.setText("高手详情");
        Bundle bundle = getIntent().getExtras();
        int where = bundle.getInt("where");

        if (where == 1) {
            HomePagerDatas.DataBean.MastersBean mb = (HomePagerDatas.DataBean.MastersBean) getIntent().getSerializableExtra("masterSBean");
            userCode = mb.getUserCode();
            Glide.with(this).load(mb.getHeadUrl()).into(circleImage);
            userName = mb.getUsername();
            tvName.setText(userName);
        } else if (where == 2) {
            Master.DataBean.MastersBean mb = (Master.DataBean.MastersBean) getIntent().getSerializableExtra("masterSBean");
            userCode = mb.getUserCode();
            Glide.with(this).load(mb.getHeadUrl()).into(circleImage);
            userName = mb.getUsername();
            tvName.setText(userName);
        } else if (where == 3) {
            userCode = bundle.getString("userCode");
            Glide.with(this).load(bundle.getString("headUrl")).into(circleImage);
            userName = bundle.getString("userName");
            tvName.setText(userName);
        }


        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ivTag.getLayoutParams();
        int screenWidth = BaseUtils.getScreenWidth(this);
        params.width = screenWidth / 6 + 5;
        params.leftMargin = screenWidth / 12;
        ivTag.setLayoutParams(params);
        Matrix matrix = new Matrix();
        matrix.postTranslate(0, 0);
        ivTag.setImageMatrix(matrix);
        vari = screenWidth / 3;
    }

    private void initData() {
        accessToken = SpUtils.getString(this, "accessToken", "");
        userId = SpUtils.getInt(this, "userId", -1);

        //1、是否登录

        //2、是否开户

        //3、是否为模拟账号
        if (userId == -1) {
            btnFollow.setVisibility(View.VISIBLE);
        } else
            masterDetailPresenter.getMasterCopyInfo(accessToken, userId, userCode);
    }

    private void initFragment() {
        dataStatisticsFragment = new SuperDataStatisticsFragment();
        tradeFragment = new SuperTradeFragment();
        tradeHistoryFragment = new SuperTradeHistoryFragment();
        mFragment = new Fragment[]{dataStatisticsFragment, tradeFragment, tradeHistoryFragment};
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.content, dataStatisticsFragment).commit();
        //默认设置为第1个
        mIndex = 0;
        setIndexSelected(0);
    }


    /**
     * 控制Fragment的显示与隐藏
     *
     * @param index
     */
    private void setIndexSelected(int index) {
        if (mIndex == index) {
            return;
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        //隐藏
        ft.hide(mFragment[mIndex]);
        //判断是否添加
        if (!mFragment[index].isAdded()) {
            ft.add(R.id.content, mFragment[index]).show(mFragment[index]);
        } else {
            ft.show(mFragment[index]);
        }
        ft.commit();
        //再次赋值
        mIndex = index;
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        rlLeft.setOnClickListener(this);
        btnFollow.setOnClickListener(this);
        btnChangeMoney.setOnClickListener(this);
        btnRemove.setOnClickListener(this);
    }

    private View view = null;

    @Override
    public void onClick(View v) {
        if (view == null)
            view = View.inflate(this, R.layout.pop_style_follow_order, null);
        TextView tvPopName = (TextView) view.findViewById(R.id.tv_pop_name);
        ImageView ivDiss = (ImageView) view.findViewById(R.id.iv_diss);
        final EditText etMoney = (EditText) view.findViewById(R.id.et_money);
        LinearLayout llOne = (LinearLayout) view.findViewById(R.id.ll_one);
        TextView tvOne = (TextView) view.findViewById(R.id.tv_one);
        TextView tvTwo = (TextView) view.findViewById(R.id.tv_two);
        TextView tvThree = (TextView) view.findViewById(R.id.tv_three);
        TextView tvFour = (TextView) view.findViewById(R.id.tv_four);
        TextView tvFourLeft = (TextView) view.findViewById(R.id.tv_four_left);
        Button btnSure = (Button) view.findViewById(R.id.btn_sure);

        switch (v.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.btn_follow:

                if (BaseUtils.isFastClick()) {
                    if (userId == -1) {
                        showMyToast("请登录后重试");
                        return;
                    }
                    if (masterCopyInfo == null) {
                        showMyToast("暂无法跟单 请稍后重试");
                        masterDetailPresenter.getMasterCopyInfo(accessToken, userId, userCode);
                        return;
                    }
                    if (masterCopyInfo.getAccStatus() == 1) {
                        showMyToast("请先申请开户");
                        return;
                    } else if (masterCopyInfo.getAccStatus() == 2) {
                        showMyToast("模拟金不支持跟单");
                        return;
                    }
                    if (masterCopyInfo.getMinAmt() == 0) {
                        showMyToast("跟单失败 请重新尝试");
                        masterDetailPresenter.getMasterCopyInfo(accessToken, userId, userCode);
                        return;
                    }

                    tag = 0;
                    btnSure.setText("确认跟单");
                    tvPopName.setText("跟单" + userName);
                    llOne.setVisibility(View.GONE);
                    tvFour.setTextColor(getResources().getColor(R.color.stock_rise_color));
                    tvFourLeft.setTextColor(getResources().getColor(R.color.stock_rise_color));
                    tvTwo.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getAvailableAmt(), 2));
                    tvThree.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getAdviceAmt(), 2));
                    tvFour.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getMinAmt(), 2));
                    popupWindow = BaseView.showPopupWindow(view, this, R.layout.activity_superman_detail, Gravity.CENTER);
                }
                break;
            case R.id.btn_change_money:
                if (BaseUtils.isFastClick()) {
                    tag = 1;
                    btnSure.setText("确认修改");
                    tvPopName.setText("修改跟单金额");
                    llOne.setVisibility(View.VISIBLE);
                    tvOne.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getUsedAmt(), 2));
                    tvTwo.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getAvailableAmt(), 2));
                    tvThree.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getAdviceAmt(), 2));
                    tvFour.setText("$" + BaseUtils.getDigitsData(masterCopyInfo.getMinAmt(), 2));
                    popupWindow = BaseView.showPopupWindow(view, this, R.layout.activity_superman_detail, Gravity.CENTER);
                }
                break;
            case R.id.btn_remove:
                showRemoveFollowDialog();
                break;
        }
        ivDiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null)
                    popupWindow.dismiss();
            }
        });
        showFollowMasterPopupWindow(etMoney, btnSure);

    }

    /**
     * 修改／跟随高手
     *
     * @param etMoney
     * @param btnSure
     */
    private void showFollowMasterPopupWindow(final EditText etMoney, Button btnSure) {
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String money = etMoney.getText().toString().trim();
                try {
                    double moneyD = Double.valueOf(money);
                    if (moneyD < masterCopyInfo.getMinAmt()) {
                        showMyToast("不能小于最低跟单金额");
                        return;

                    } else if (moneyD > masterCopyInfo.getAvailableAmt()) {
                        showMyToast("不能超出账户可用余额");
                        return;

                    }
                } catch (Exception e) {
                    showMyToast("请输入有效金额");
                    return;
                }
                if (!TextUtils.isEmpty(money)) {
                    if (tag == 0) {//跟单
                        masterDetailPresenter.copyMaster(accessToken, userId, userCode, money, 0);
                    } else if (tag == 1) {//修改
                        masterDetailPresenter.copyMaster(accessToken, userId, userCode, money, 1);
                    }
                    if (popupWindow != null)
                        popupWindow.dismiss();

                } else {
                    MyApplication.showToast(getApplicationContext(), "复制金额不能为空");
                }

            }
        });
    }

    /**
     * 解除跟随关系对话框
     */
    private void showRemoveFollowDialog() {
        CustomDialog menuDialog = new CustomDialog(this, R.style.customDialogStyle);
        menuDialog.setCancelable(true);
        //取消复制并跟随高手平仓
        menuDialog.setTakePhotoRunnable(new Runnable() {
            @Override
            public void run() {
                masterDetailPresenter.cancelMasterCopy(accessToken, userId, userCode, 0);
            }
        });
        //取消复制并强制平仓
        menuDialog.setTakePictureRunnable(new Runnable() {
            @Override
            public void run() {
                masterDetailPresenter.cancelMasterCopy(accessToken, userId, userCode, 1);
            }
        });
        menuDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CloseAllActivity.getScreenManager().popActivity(this);

    }


    @OnClick({R.id.ll_one, R.id.ll_two, R.id.ll_three})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_one:
                setIndexSelected(0);
                animation = new TranslateAnimation(offset, 0, 0, 0);
                offset = 0;
                setMyTextColor(0);
                break;
            case R.id.ll_two:
                setIndexSelected(1);
                animation = new TranslateAnimation(offset, vari, 0, 0);
                offset = vari;
                setMyTextColor(1);
                break;
            case R.id.ll_three:
                setIndexSelected(2);
                animation = new TranslateAnimation(offset, 2 * vari, 0, 0);
                offset = 2 * vari;
                setMyTextColor(2);
                break;
        }
        animation.setDuration(300);
        animation.setFillAfter(true);
        ivTag.startAnimation(animation);
    }

    private void setMyTextColor(int tag) {
        if (tag == 0) {
            ivOne.setImageResource(R.mipmap.yellow_data_count);
            tvOne.setTextColor(getResources().getColor(R.color.main_color));
            ivTwo.setImageResource(R.mipmap.gray_real_tration);
            tvTwo.setTextColor(getResources().getColor(R.color.main_text_color));
            ivThree.setImageResource(R.mipmap.gray_history_tration);
            tvThree.setTextColor(getResources().getColor(R.color.main_text_color));

        } else if (tag == 1) {

            ivOne.setImageResource(R.mipmap.gray_data_count);
            tvOne.setTextColor(getResources().getColor(R.color.main_text_color));
            ivTwo.setImageResource(R.mipmap.yellow_real_tration);
            tvTwo.setTextColor(getResources().getColor(R.color.main_color));
            ivThree.setImageResource(R.mipmap.gray_history_tration);
            tvThree.setTextColor(getResources().getColor(R.color.main_text_color));
        } else {

            ivOne.setImageResource(R.mipmap.gray_data_count);
            tvOne.setTextColor(getResources().getColor(R.color.main_text_color));
            ivTwo.setImageResource(R.mipmap.gray_real_tration);
            tvTwo.setTextColor(getResources().getColor(R.color.main_text_color));
            ivThree.setImageResource(R.mipmap.yellow_history_tration);
            tvThree.setTextColor(getResources().getColor(R.color.main_color));
        }
    }


    /**
     * 用于短时间加载的dialog
     */
    public void showShortDialog() {
        if (shortDialog == null) {
            shortDialog = new MyProgressDialog(this);
            shortDialog.setCancelable(false);
        }
        shortDialog.show();
    }

    public void dismissShortDialog() {
        if (shortDialog != null)
            shortDialog.dismiss();
    }

    public void setSomeData(double totalProfitRate, double maxRetract, int lastTotalClose, double lastProfitCloseRate) {
        tvAllYield.setText(totalProfitRate + "%");
        tvMaxRetract.setText(maxRetract + "%");
        tvTotalClose.setText(lastTotalClose + "笔");
        tvProfitCloseRate.setText(lastProfitCloseRate + "%");
    }

    @Override
    public void showDialog() {
        showShortDialog();
    }

    @Override
    public void dismissDialog() {
        dismissShortDialog();
    }

    @Override
    public void showMyToast(String str) {
        try {
            MyApplication.showToast(this, str);
        } catch (Exception e) {

        }
    }

    @Override
    public void showMasterCopyInfo(MasterCopyInfo.DataBean.CopyInfoBean masterCopyInfo) {
        if (llFollowed == null) return;
        this.masterCopyInfo = null;
        this.masterCopyInfo = masterCopyInfo;
        if (masterCopyInfo.getAccStatus() == 1) {//未开户
            btnFollow.setVisibility(View.VISIBLE);
            return;
        } else if (masterCopyInfo.getAccStatus() == 2) {//模拟账户
            btnFollow.setVisibility(View.VISIBLE);
            return;
        } else if (masterCopyInfo.getAccStatus() == 3) {//真实账户
            if (masterCopyInfo.getIsCopy() == 0) {
                btnFollow.setVisibility(View.VISIBLE);
                llFollowed.setVisibility(View.GONE);
            } else {
                btnFollow.setVisibility(View.GONE);
                llFollowed.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void showMasterCopyMasterResult(String result) {
        showMyToast(result);
        masterDetailPresenter.getMasterCopyInfo(accessToken, userId, userCode);
        EventBus.getDefault().post(new EventDatas(EventContents.FOLLOW_ORDER_DETAIL_ACTIVITY, ""));

    }

    @Override
    public void showMasterCancleCopyResult(String result) {
        showMyToast(result);
        masterDetailPresenter.getMasterCopyInfo(accessToken, userId, userCode);
        EventBus.getDefault().post(new EventDatas(EventContents.FOLLOW_ORDER_DETAIL_ACTIVITY, ""));
        EventBus.getDefault().post(new EventDatas(EventContents.STOP_LOSS_OR_PROFIT_FINISH_TRADE, null));

    }
}
